import { Decoder, tools, Reader } from 'EBML'

// 下载MediaRecorder录制的视频（解决视频无时长问题）
export const exportVideo = (blob) => {

    const reader = new Reader()

    const decoder = new Decoder()


    const fileReader = new FileReader()

    fileReader.onload = function () {

        // 1.解析视频blob

        const ebmlList = decoder.decode(this.result)

        ebmlList.forEach(item => reader.read(item))

        reader.stop()

        // 2.获取元数据

        const refinedMetadataBuf = tools.makeMetadataSeekable(
            reader.metadatas,
            reader.duration,
            reader.cues
        )

        // 3.获取元数据大小

        const body = this.result.slice(reader.metadataSize)

        // 4.写入元数据

        const newBlob = new Blob([refinedMetadataBuf, body], {
            type: 'video/webm;'
        })

        // 5.将blob转成url
        const refinedUrl = URL.createObjectURL(newBlob)

        // 6.自动下载
        download(refinedUrl, 'webm')
    }
    fileReader.readAsArrayBuffer(blob)
}

// 普通下载
export function download(url, type) {
    let link = document.createElement("a");
    link.href = url;
    link.download = Date.now() + "." + type;
    link.download = `${new Date().toLocaleString().replaceAll('/', '-').replaceAll(':', '_')}.${type}`;
    link.click();
    link = null;
}